#! /usr/bin/python3
# -*- coding: utf-8 -*-

# This code shows an example of text translation from English to Simplified-Chinese.
# This code runs on Python 2.7.x and Python 3.x.
# You may install `requests` to run this code: pip install requests
# Please refer to `https://api.fanyi.baidu.com/doc/21` for complete api document

import requests
import random
import json
import pyperclip
from hashlib import md5
import vim

def __do_visual(buff, cur, res=''):
    cursor = cur.window.cursor
    if buff.mark('<')[0] == buff.mark('>')[0]:

        return buff[
            buff.mark('<')[0] - 1][
                buff.mark('<')[1]:buff.mark('>')[1]]
    else:
        res = buff[buff.mark('<')[0] - 1][buff.mark('<')[1]:]

        for x in range(buff.mark('>')[0] - buff.mark('<')[0] - 1):
            res = ' '.join((res, buff[buff.mark('<')[0] + x]))
            #print("第{}次循环: ".format(x)+res)
        return ' '.join((
            res,
            buff[buff.mark('>')[0] - 1][:buff.mark('>')[1]]))

def translate(res):
    # res需要翻译的字符串
    query = res
    # Set your own appid/appkey.
    appid = '20211105000991769'
    appkey = 'BGMumlXi6QJWE0mmcjCd'

    # For list of language codes, please refer to `https://api.fanyi.baidu.com/doc/21`
    from_lang = 'en'
    to_lang =  'zh'

    endpoint = 'http://api.fanyi.baidu.com'
    path = '/api/trans/vip/translate'
    url = endpoint + path

    # Generate salt and sign
    def make_md5(s, encoding='utf-8'):
        return md5(s.encode(encoding)).hexdigest()

    salt = random.randint(32768, 65536)
    sign = make_md5(appid + query + str(salt) + appkey)

    # Build request
    headers = {'Content-Type': 'application/x-www-form-urlencoded'}
    payload = {'appid': appid, 'q': query, 'from': from_lang, 'to': to_lang, 'salt': salt, 'sign': sign}

    # Send request
    r = requests.post(url, params=payload, headers=headers)
    result = r.json()
    return result['trans_result'][0]['dst']

def vim_gtranslate():
    to_lang = vim.eval('g:gtrans_output_language') or 'zh-cn'

    buff = vim.current.buffer
    cur = vim.current
    cursor = cur.window.cursor
    res = ''
    if buff.mark('<') and buff.mark('>') and cursor[1] == 0 \
            and buff.mark('<')[0] <= cursor[0] <= buff.mark('>')[0]:
        # visual mode
        res = __do_visual(buff, cur)
    else:
        # cursor mode
        res = vim.eval('expand("<cword>")')

    translated = ''
    try:
        translated = translate(res if res else '')
    except Exception:
        pass
    vim.command (':call s:ShowTransWindow("%s")' % translated)
